import { _decorator, Component, Node, director, System, Eventify, log, js, sys } from 'cc';
import { sdk } from '../SDKManager';
const { ccclass, property } = _decorator;

declare const tt;

@ccclass('ByteDanceManager')
class ByteDanceManager extends Eventify(System) {

    public static instance: ByteDanceManager;
    static ID = 'bytedance_system';

    registerSystem() {
        director.unregisterSystem(director.getSystem(ByteDanceManager.ID));
        director.registerSystem(ByteDanceManager.ID, bdm, System.Priority.MEDIUM);
        bdm.init();
    }

    init() {
        log(`<${js.getClassName(this)}>`, 'init');
    }

    loginResolve: (value: boolean) => void = null;

    gameLogin() {
        if (sys.platform == sys.Platform.BYTEDANCE_MINI_GAME) {
            return new Promise(resolve => {
                this.loginResolve = resolve;
                console.log(`抖音小游戏登录`);
                const self = this;
                globalThis.tt.login({
                    force: true,
                    success(res) {
                        console.log(`login 调用成功${res.code} ${res.anonymousCode}`);
                        // 获取用户授权信息，若没有授权请求用户授权
                        self.ByteDanceGameSetting();
                    },
                    fail(res) {
                        console.log(`login 调是用失败`);
                    },
                });
            });
        }
        else if (sys.platform == sys.Platform.WECHAT_GAME) {
            return globalThis.WechatManager.instance.gameLogin();
        }
        else {
            return new Promise(resolve => {
                resolve(true);
            });
        }
    }

    /**
     * 字节跳动平台 登录、授权、请求用户信息、实名认证
     */
    private ByteDanceGameLogin() {
        console.log(`抖音小游戏登录`);
        const self = this;
        globalThis.tt.login({
            force: true,
            success(res) {
                console.log(`login 调用成功${res.code} ${res.anonymousCode}`);
                // 获取用户授权信息，若没有授权请求用户授权
                self.ByteDanceGameSetting();
            },
            fail(res) {
                console.log(`login 调是用失败`);
            },
        });
    }
    private ByteDanceGameSetting() {
        console.log(`抖音小游戏获取授权信息`);
        const self = this;
        globalThis.tt.getSetting({
            success: (res) => {
                if (res.authSetting['scope.userInfo']) {
                    console.log(`已经获得用户信息授权,请求用户信息 `, res);
                    self.ByteDanceGameGetUserInfo();
                } else {
                    console.log(`还没有获得用户信息授权，请求用户授权`, res);
                    self.ByteDanceGameAuthorize();
                }
            }
        });
    }
    private ByteDanceGameAuthorize() {
        console.log(`抖音小游戏获取授权信息`);
        const self = this;
        globalThis.tt.authorize({
            scope: "scope.userInfo",
            success(res) {
                console.log(`用户授权成功`, res);
                self.ByteDanceGameGetUserInfo();
            },
            fail(res) {
                console.log(`用户授权失败`, res);
                self.loginResolve && self.loginResolve(false);
            },
        })
    }
    private ByteDanceGameGetUserInfo() {
        console.log(`抖音小游戏获取用户信息信息`);
        let self = this;
        globalThis.tt.getUserInfo({
            // withCredentials: true,
            withRealNameAuthenticationInfo: true,
            success(res) {
                let info = res.userInfo
                if (res.realNameAuthenticationStatus == "certified") {
                    console.log(`已实名认证`);
                    self.loginResolve && self.loginResolve(true);
                } else {
                    console.log(`未实名认证`);
                    self.ByDanceGameRealName();
                }
            },
            fail(res) {
                console.log(`getUserInfo 调用失败`, res.errMsg);
            },
        });
    }
    private ByDanceGameRealName() {
        let self = this;
        globalThis.tt.authenticateRealName({
            success(res) {
                console.log("用户实名认证成功", res);
                self.loginResolve && self.loginResolve(true);
            },
            fail(res) {
                console.log("用户实名认证失败", res.errMsg);
                self.loginResolve && self.loginResolve(false);
            },
        });

        globalThis.tt.onRealNameAuthenticationComplete(function (res) {
            console.log("实名认证完成回调", res);
            self.loginResolve && self.loginResolve(true);
        })
    }

    report(eventName: string, data: Record<string, string | number>) {
        console.log('report', eventName, data);
        if (sys.platform == sys.Platform.BYTEDANCE_MINI_GAME) {
            globalThis.tt.reportAnalytics(eventName, data);
        }
    }

    ImRankFuncEnabled() {
        if (typeof (globalThis.tt?.setImRankData) == 'function' &&
            typeof (globalThis.tt?.getImRankList) == 'function') {
            return true;
        }
    }

    /**
     * 设置排行榜
     * @param dataType      0：数字类型 、 1：字符串类型
     * @param value         dataType == 0 时只能传正数的字符串;若dataType为1，则传入字符串
     * @param priority      dataType 为 0 时，不填即可;dataType 为 1 时，需要传入这个值判断权重
     * @param extra         预留字段
     */
    setImRankData(data: Record<string, string | number>) {
        if (!this.ImRankFuncEnabled()) return;
        globalThis.tt.setImRankData({
            dataType: data.dataType,
            value: data.value,
            priority: data.priority,
            extra: data.extra,

            success(res) {
                console.log(`setImRankData success res: `, res);
            },
            fail(res) {
                console.log(`setImRankData fail res: `, res.errMsg);
            },
        });
    }

    /**
     * 获取排行榜
     * @param relationType  default: 好友及总榜都展示; friend：仅好友排行榜; all：仅总榜单
     * @param dataType      0:数字类型；1：字符串类型
     * @param rankType      day,week,month,all
     * @param suffix        数据后缀
     * @param rankTitle     排行榜标题的文案
     */
    getImRankList(data: Record<string, string | number>) {
        if (!this.ImRankFuncEnabled()) return;
        globalThis.tt.getImRankList({
            relationType: data.relationType,
            dataType: data.dataType,
            rankType: data.rankType,
            suffix: data.suffix,
            rankTitle: data.rankTitle,

            success(res) {
                console.log(`getImRankData success res: `, res);
            },
            fail(res) {
                console.log(`getImRankData fail res: `, res.errMsg);
            },
        });
    }

    /**
     * 检查小游戏快捷方式是否已添加到手机桌面上，仅 Android 支持
     */
    checkShortcut() {
        globalThis.tt.checkShortcut({
            success(res) {
                console.log("检查快捷方式", res.status);
            },

            fail(res) {
                console.log("检查快捷方式失败", res.errMsg);
            }
        })
    }

    /**
     * 可以将小游戏快捷方式添加到手机桌面上
     */
    addShortcut() {
        globalThis.tt.addShortcut({
            success() {
                console.log("添加桌面成功");
            },

            fail(err) {
                console.log("添加桌面失败", err.errMsg);
            }
        })
    }

    vibrateShort() {
        tt.vibrateShort({
            success() { },
            fail() { }
        });
    }

    vibrateLong() {
        tt.vibrateLong({
            success() { },
            fail() { }
        });
    }

    getEnvInfoSync(): {
        microapp: {
            mpVersion: string,
            envType: string, // production development preview
            appId: string
        }, common: {
            USER_DATA_PATH: string
        }
    } {
        if (sys.platform == sys.Platform.BYTEDANCE_MINI_GAME) {
            return globalThis.tt.getEvnInfoSync?.();
        }
    }

    getSystemInfo(callback: { useCache: boolean, success: () => void, fail: () => void, complete: () => void }) {
        if (sys.platform == sys.Platform.BYTEDANCE_MINI_GAME) {
            return globalThis.tt.getSystemInfo?.(callback);
        }
    }

    getDeviceInfoSync() {
        if (sys.platform == sys.Platform.BYTEDANCE_MINI_GAME) {
            return globalThis.tt.getDeviceInfoSync?.();
        }
    }

    getSystemInfoSync(useCache: boolean) {
        if (sys.platform == sys.Platform.BYTEDANCE_MINI_GAME) {
            return globalThis.tt.getSystemInfoSync?.(useCache);
        }
        // SDKUpdateVersion: "2.84.1.11"
        // SDKVersion: "2.84.1"
        // appName: "devtools"
        // battery: 100
        // brand: "devtools"
        // devicePixelRatio: 3
        // deviceScore: {cpu: 7.905, gpu: 9.0622, memory: 7.0344, overall: 7.9524}
        // fontSizeSetting: 16
        // language: "zh_CN"
        // model: "iPhone 12"
        // nativeSDKVersion: "10.3.0"
        // pixelRatio: 3
        // platform: "devtools"
        // safeArea: {left: 0, right: 390, top: 47, bottom: 810, width: 390, …}
        // screenHeight: 844
        // screenWidth: 390
        // statusBarHeight: 47
        // system: "iOS 14"
        // version: "6.6.3"
        // wifiSignal: 4
        // windowHeight: 844
        // windowWidth: 390
    }

    shareAppMessage() {
        if (globalThis.tt?.shareAppMessage) {
            globalThis.tt.shareAppMessage({
                templateId: "21i156c1g46bb25p64",
                success() {
                    console.log("分享成功");
                    sdk.onShareAppMessageCommand.execute();
                },
                fail(e) {
                    console.log("分享失败");
                },
            });
        }
    }
}

globalThis.ByteDanceManager = ByteDanceManager;

export const bdm = ByteDanceManager.instance = new ByteDanceManager();